﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using AutoPartsSearch.Web.App_Start;
using AutoPartsSearch.Web.Infrastructure;
using Griffin.MvcContrib.Localization;
using AutoPartsSearch.Domain.Abstract;
using System.Security.Principal;
using System.Web.Security;
using AutoPartsSearch.Domain.Entities.Enums;

namespace AutoPartsSearch.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            ModelBinders.Binders[typeof (IPrincipal)] = new PrincipalModelBinder();

            ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
            DependencyResolver.SetResolver(new NinjectControllerFactory());

            CreateRoles();
            SetupLocalicationProviders();
            AutoMapperConfig.CreateMaps();
        }

        private void SetupLocalicationProviders()
        {
            ModelValidatorProviders.Providers.Clear();
            ModelMetadataProviders.Current = new LocalizedModelMetadataProvider();
            ModelValidatorProviders.Providers.Add(new LocalizedModelValidatorProvider());
        }

        protected void Application_AcquireRequestState(object sender, EventArgs e)
        {
            var langugaeGetter = DependencyResolver.Current.GetService<ILanguageGetter>();
            var ci = langugaeGetter.GetCurrentLanguage();

            Thread.CurrentThread.CurrentUICulture = ci;
            Thread.CurrentThread.CurrentCulture = ci;
        }

        private void CreateRoles()
        {
            if (!Roles.RoleExists(Role.Seller.ToString()))
            {
                Roles.CreateRole(Role.Seller.ToString());
            }
            if (!Roles.RoleExists(Role.Administrator.ToString()))
            {
                Roles.CreateRole(Role.Administrator.ToString());
            }
        }

    }
}